#import "LoginViewController.h"
#import "SBJsonParser.h"
#import "RegexKitLite.h"
#import "UserManager.h"
#import "RegisterViewController.h"
#import "ColdAppDelegate.h"
#import "UMSocialAccountEntity.h"
#import "NetWorkManager.h"

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc {
    PP_RELEASE(hudLoading);
    PP_RELEASE(email);
    PP_RELEASE(password);
    PP_RELEASE(loginBtn);
    PP_RELEASE(userInfo);
    PP_RELEASE(userInfo);
    PP_RELEASE(statuses);
    PP_RELEASE(loginBgImageView);
    PP_RELEASE(loginUserImage);
    PP_RELEASE(loginPasswordImage);
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor]; //导航上那条黑线的原因在这里
    
    self.navigationController.view.layer.cornerRadius = 4;
    self.navigationController.view.layer.masksToBounds = YES;
    self.navigationController.navigationBar.layer.cornerRadius = 4;
    self.navigationController.navigationBar.layer.masksToBounds = YES;
    
    baseTitle.text = @"登录";

    UIButton* backBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)] autorelease];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_1.png"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_2.png"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backBarBtn= [[[UIBarButtonItem alloc] initWithCustomView:backBtn] autorelease];
    [self.navigationItem setLeftBarButtonItem:backBarBtn];
    
    UIButton *registerBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)] autorelease];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn setTitle:@"注册" forState:UIControlStateHighlighted];
    [registerBtn setTitleColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0] forState:UIControlStateNormal];
    [registerBtn setTitleColor:[UIColor colorWithRed:0.0/255.0 green:157.0/255.0 blue:212.0/255.0 alpha:1.0] forState:UIControlStateHighlighted];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [registerBtn addTarget:self action:@selector(goToRegister) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* postBarBtn= [[[UIBarButtonItem alloc] initWithCustomView:registerBtn] autorelease];
    [self.navigationItem setRightBarButtonItem:postBarBtn];
    [registerBtn release];
    
//    UIImage *loginBgNormal = nil;
//    UIImage *loginBgClick = nil;
    
//    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
//    if (version >= 5.0){
//        loginBgNormal = [[UIImage imageNamed:@"input_click_1.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
//        loginBgClick = [[UIImage imageNamed:@"input_click_2.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
//    }else{
//        loginBgNormal = [[UIImage imageNamed:@"input_click_1.png"] stretchableImageWithLeftCapWidth:21 topCapHeight:14];
//        loginBgClick = [[UIImage imageNamed:@"input_click_2.png"] stretchableImageWithLeftCapWidth:21 topCapHeight:14];
//    }
//    [loginBtn setBackgroundImage:loginBgNormal forState:UIControlStateNormal];
//    [loginBtn setBackgroundImage:loginBgClick forState:UIControlStateHighlighted];
    
    UIImage *loginBgImage = [[UIImage imageNamed:@"login_bg.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:21];
    loginBgImageView.image = loginBgImage;
    
    UIImage *loginBtnBgImageOne = [[UIImage imageNamed:@"login_btn_1.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:21];
    UIImage *loginBtnBgImageTwo = [[UIImage imageNamed:@"login_btn_2.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:21];
    [loginBtn setBackgroundImage:loginBtnBgImageOne forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:loginBtnBgImageTwo forState:UIControlStateHighlighted];
    
    
    email = [[UITextField alloc] initWithFrame:CGRectMake(loginUserImage.frame.origin.x +40, loginUserImage.frame.origin.y-8, 230, 40)];
    email.delegate = self;
    email.keyboardType = UIKeyboardTypeEmailAddress;
    email.returnKeyType = UIReturnKeyNext;
    email.borderStyle = UITextBorderStyleNone;
    email.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
    if( [UserManager sharedInstance].email != nil ){
        email.text = [UserManager sharedInstance].email;
    }else{
        email.placeholder = @"账号";
    }
    [email addTarget:self action:@selector(textFieldGoToNext:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    
    password = [[UITextField alloc] initWithFrame:CGRectMake(loginPasswordImage.frame.origin.x +40, loginPasswordImage.frame.origin.y-8, 230, 40)];
    password.delegate = self;
    password.returnKeyType = UIReturnKeyDone;
    password.borderStyle = UITextBorderStyleNone;
    password.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
    password.placeholder = @"密码";
    [password setSecureTextEntry:YES];
    [password addTarget:self action:@selector(textFieldGoToNext:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.view addSubview:email];
    [self.view addSubview:password];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    if ([UserManager sharedInstance].isLogin) {
        [self back:self];
    }
    [email becomeFirstResponder];
}

- (void)goToRegister {
    [email resignFirstResponder];
    [password resignFirstResponder];
    RegisterViewController *viewController = [[RegisterViewController alloc] init];
//    viewController.resultDelegate = self;
    viewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    BaseNavigationController *nav = [[BaseNavigationController alloc]initWithRootViewController:viewController];
    [self presentModalViewController:nav animated:YES];
    [viewController release];
    
}

- (void)viewDidUnload
{
    PP_RELEASE(hudLoading);
    PP_RELEASE(email);
    PP_RELEASE(password);
    PP_RELEASE(loginBtn);
    PP_RELEASE(userInfo);
    PP_RELEASE(userInfo);
    PP_RELEASE(statuses);
    PP_RELEASE(loginBgImageView);
    PP_RELEASE(loginUserImage);
    PP_RELEASE(loginPasswordImage);
    [super dealloc];[super viewDidUnload];
}

-(IBAction)textFieldGoToNext:(id)sender
{
    if( sender == email ){
        [sender resignFirstResponder];
        [password becomeFirstResponder];
    }else if(sender == password){
        [sender resignFirstResponder];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



- (IBAction)doLogin
{
    [email resignFirstResponder];
    [password resignFirstResponder];

    if (![email.text isMatchedByRegex:@"^[\\w\\.-]+@[\\w\\.-]+\\.\\w{2,4}$"]){
        [self baseShowInfoHud:NSLocalizedString(@"请输入正确的邮箱", @"") andIsTop:YES];
        [email becomeFirstResponder];
        return;
    }
    
    //密码验证
    if (![password.text isMatchedByRegex:@"^\\S{6,}$"]) {
        [self baseShowInfoHud:NSLocalizedString(@"密码不少于6位", @"") andIsTop:YES];
        [password becomeFirstResponder];
        password.text = nil;
        return;
    }
    
    HAS_NO_NETWORK(self);
    
    hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hudLoading.labelText = @"正在登录...";
    hudLoading.opacity = PP_mbprogressHudOpacity;

    UserManager *tUserManager = [UserManager sharedInstance];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *err = [tUserManager loginWithEmail:email.text password:password.text remember:@"on"];
        if ([err isEqualToString:@""] || err == nil) {
            err = PP_loginErrorInfo;
        }
        sleep(1);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(![tUserManager isLogin]){
                hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Wrong.png"]] autorelease];
                hudLoading.labelText = err;
                hudLoading.mode = MBProgressHUDModeCustomView;
                [hudLoading hide:YES afterDelay:1];                
                
            }else{
                [hudLoading hide:YES];
                [self back:self];
            }
        });
    });
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

        switch (indexPath.row) {
            case 0://
                cell.accessoryView = email;
                break;
            case 1://
                cell.accessoryView = password;
                break;
            default://
                break;
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}

-(void) back:(id)sender
{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    if ([self respondsToSelector:@selector(presentingViewController)]) {
        
        if (self.presentedViewController) {
            [[self presentedViewController] dismissModalViewControllerAnimated:YES];
        }
        else {
            [self dismissModalViewControllerAnimated:YES];
        }
    }
    else {
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
    }
}


#pragma mark - UMSocialDelegate

//-(void)didFinishGetUMSocialDataResponse:(UMSocialResponseEntity *)response
//{
//    Log(@"social Account response is %@",response);
//    
//}
//
//-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
//{
//    Log(@"didFinishGetUMSocialDataInViewController is %@",response);
//    if (response.viewControllerType == UMSViewControllerOauth) {
//        UMSocialAccountEntity *account = (UMSocialAccountEntity *)[_socialUIController.socialData.socialAccount objectForKey:[UMSocialAccountEntity getSnsPlatformString:_selectOauthType]];
//        if (account.userName != nil && account.userName.length > 0) {
//            _nickNameLabel.text = @"nickNameSuccess";
//        }
//        if (account.accessToken != nil&& account.accessToken.length > 0) {
//            _accessTokenLable.text = @"accessTokenSuccess";
//        }
//    }
//}

-(void)didCloseUIViewController:(UMSViewControllerType)fromViewControllerType
{
//    Log(@"fromViewControllerType is %d",fromViewControllerType);
//    Log(@"didCloseUIViewController account is %@",(UMSocialAccountEntity *)[socialController.socialData.socialAccount objectForKey:@"sina"] );
}

#pragma mark - 
#pragma mark -------新浪微博登录---

//- (void)sinaweiboFromColdApp
//{
//    ColdAppDelegate *delegate = (ColdAppDelegate *)[UIApplication sharedApplication].delegate;
//     sinaWeiboLogin = delegate.sinaWeiboLogin;
//}
//
//新浪微博登录
//- (IBAction)sinaLogin:(id)sender {
//    Log(@"LoginViewCongroller <sinaLogin> start");
//    socialController = [[UMSocialControllerService alloc] initWithUMSocialData:[UMSocialData defaultData]];
//    UINavigationController *accountViewController =[socialController getSocialOauthController:UMSocialSnsTypeSina];
//    socialController.soicalUIDelegate = self;
//    [self presentModalViewController:accountViewController animated:YES];
//        
//    UINavigationController *oauthController = [socialControllerService getSocialOauthController:shareToType];
//    [self presentModalViewController:oauthController animated:YES];
//    [socialController.socialDataService requestSocialAccount];

//    Log(@"sinaLogin start:%@",sinaWeiboLogin);
//    [self sinaweiboFromColdApp];
//    Log(@"sinaLogin start after:%@......%@",sinaWeiboLogin,sinaWeiboLogin.delegate);
//    
//    [sinaWeiboLogin logIn];
//}
//
//qq登录
//- (IBAction)qqLogin:(id)sender {
//    Log(@"LoginViewCongroller <qqLogin> start");
//    socialController = [[UMSocialControllerService alloc] initWithUMSocialData:[UMSocialData defaultData]];
//    UINavigationController *accountViewController =[socialController getSocialOauthController:UMSocialSnsTypeQzone];
//    socialController.soicalUIDelegate = self;
//    [self presentModalViewController:accountViewController animated:YES];
//}
//
//- (void)removeAuthData
//{
//    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
//}



@end
